var express = require('express');
var router = express.Router();
var DB = require('../database/DB');
function Page() {
	this.page = 1;
	this.rows = 10;
	this.data = {};
	this.count = 0;
	this.totalCount = 0;
	this.totalPage = 0;
	this.setTotalConunt = function(count) {
		this.totalPage = count <= this.rows ? 1 : (count % this.rows === 0 ? parseInt(count / this.rows) : parseInt(count / this.rows) + 1);
	};
}
router.post('/saveOrUpdate.do', function(req, res, next) {
	var person = req.body;
	if (person.id === undefined) {
		DB.Person.insert(person);
	} else {
		DB.Person.update(person);
	}
	res.end('"success"');
});

router.post('/del.do', function(req, res, next) {
	DB.Person.del(req.body.id);
	res.end('"success"');
});

router.post('/searchList.do', function(req, res, next) {
	var params = {
		keywords : req.body.keywords ? req.body.keywords : '',
		sex : req.body.sex ? req.body.sex : '',
		page : (parseInt(req.body.page) > 0 ? parseInt(req.body.page) : 1),
		rows : (parseInt(req.body.rows) > 0 ? parseInt(req.body.rows) : 10)
	};
	DB.Person.searchListCount(params, function(data) {
		var totalCount = data[0].num;
		DB.Person.searchList(params, function(rows) {
			var page = new Page();
			page.data = rows;
			page.count = rows.length;
			page.setTotalConunt(totalCount);
			res.send(JSON.stringify(page));
		});
	});
});

router.post('/birthdayList.do', function(req, res, next) {
	DB.Person.listBirthdayByMonth(req.body.month, function(rows) {
		var page = new Page();
		page.data = rows;
		page.count = rows.length;
		page.setTotalConunt(rows.length);
		res.send(JSON.stringify(page));
	});
});

module.exports = router;